import { _pick, reduceToObject } from "mmb";
import { AppCTX } from "../../types/koaExtend";
import { createBrandApiMWRouter } from "../../middleware/brand-api/brandAdminChecker";
import pageMW from "../../middleware/pager";
import {
  listNormalBrandDistributorWithUsersByBrandID,
  updateBrandDistributor,
} from "../../service/brandDistributorService";
import { listAggsToUserRecentNewses } from "../../service/userPvLogService";
const router = createBrandApiMWRouter();

// 获取品牌分销员列表
router.get(
  "brand-distributors",
  "/brd/:brandId/distributors",
  pageMW,
  async (ctx: AppCTX, next) => {
    const { brandId } = ctx.params;
    let { keyword } = ctx.query;
    const { userId, limit, offset, ts } = ctx;

    const { total, items } = await listNormalBrandDistributorWithUsersByBrandID(
      { brandId, keyword },
      {
        limit,
        offset,
        ts,
      }
    );
    const followerRecentNews = await listAggsToUserRecentNewses(
      items.map((it) => it.userId)
    );
    const recentNewsMap = reduceToObject(
      followerRecentNews,
      (o) => o.userId,
      (o) => o.latestTime
    );

    ctx.body = {
      total,
      rows: items.map((it) => ({
        recentNews: recentNewsMap[it.userId],
        ..._pick(
          it,
          "brandDistributorId",
          "aliasName",
          "distributeActivityCount",
          "saleAmount",
          "distributorUserNickName",
          "distributorUserPic",
          "fansCount"
        ),
      })),
    };
  }
);

// 备注品牌分销员名称
router.put(
  "/brd/:brandId/distributor/alias/:brandDistributorId",
  async (ctx: AppCTX, next) => {
    const { brandId, brandDistributorId } = ctx.params;
    const { aliasName } = ctx.request.body;
    const { userId } = ctx;
    //1 userId(操作人不是分销员),报错

    const brandDistributor = await updateBrandDistributor({
      brandDistributorId,
      aliasName,
    });

    ctx.body = {
      ..._pick(brandDistributor, "brandDistributorId", "brandId", "aliasName"),
    };
  }
);

export default router;
